<template>
    <el-select v-model="state.selected" class="m-2" placeholder="Select" 
    @change="change"
    size="large">
        <el-option v-for="item in state.options" :key="item" :label="item" :value="item" />
    </el-select>
    {{ state.selected }}
    <el-text> 数量：{{ state.data.length }} </el-text>
    <CopyStocksToClipboard :data="state.data" />
    <el-button @click="multi()">multi</el-button>

    <el-table :data="state.data" height="900" 
    :default-sort="state.sort"
    @sort-change="sortChange"
    @cell-click="cellClick"
    :cell-class-name="tableCellClassName"
    show-summary
    :summary-method="summaryMethod"
    style="width: 100%">
        <el-table-column prop="date" label="date"  width="210" sortable/>
        <el-table-column prop="category" label="category"  width="80" sortable/>
        <el-table-column prop="stock" label="股票" width="140" />
        <el-table-column prop="industry" label="industry"  width="120" sortable show-overflow-tooltip/>
        <el-table-column label="display" width="160">
            <template #default="scope">
                <ToDisplay :stock="scope.row.stock" :date="scope.row.date" :content="'d'"/>
                <ToMeanLine :stock="scope.row.stock" :date="scope.row.date" :content="'m'"/>
            </template>
        </el-table-column>
        <el-table-column prop="weekPct" label="week_pct"  width="80" sortable/>
        <el-table-column prop="nextWeekPct" label="next_week_pct"  width="80" sortable/>
        <el-table-column prop="disPct" label="disPct"  width="80" sortable/>
        <el-table-column prop="lp" label="lp"  width="80" sortable/>
        <el-table-column prop="curDisDuration" label="距今周数" width="80" sortable/>
        <el-table-column prop="duration" label="持续周数" width="80" sortable/>
        <el-table-column prop="curPct" label="curPct" width="100" sortable/>
        <el-table-column prop="cur60wPct" label="cur60wPct" width="100" sortable/>
        <el-table-column prop="incNum" label="incNum" width="80" sortable/>
        <el-table-column prop="pctSum" label="pctSum" width="80" sortable>
            <template #default="scope">
                {{ numberFormat(scope.row.pctSum, 2) }}
            </template>
        </el-table-column>
        <el-table-column prop="minDate" label="minDate" width="120" sortable>
            <template #default="scope">
                {{ scope.row.minDate.substring(0, 9)}}
            </template> 
        </el-table-column>
        <el-table-column prop="minPct" label="minPct" width="120" sortable/>
        <el-table-column prop="maxDate" label="maxDate" width="120" sortable>
            <template #default="scope">
                {{ scope.row.maxDate.substring(0, 9)}}
            </template> 
        </el-table-column>
        <el-table-column prop="maxPct" label="maxPct" width="120" sortable/>
    </el-table>
</template>

<script setup>
// 个股周数据详情页
import { reactive, watch } from 'vue';
import { getGB60WLowData, getGB60WTopData } from '../../service/gbSta';
import { getLpClassName, numberFormat } from '../../utils/help';
import CopyStocksToClipboard from '../CopyStocksToClipboard.vue';
import ToDisplay from '../element/ToDisplay.vue';
import { useRouteQuery } from '../../utils/useRoute';
import { openNewTableMulti } from '../../router';
import ToMeanLine from '../element/ToMeanLine.vue';


const baseKey = "MonitorPrice"
const selectKey = baseKey + "Select"
const sortPropKey = baseKey + "SortProp"
const sortOrderKey = baseKey + "SortOrder"

const props = defineProps({
    dtype: String
})

const state = reactive({
    operationSelected: "",
    selected:"",
    rawData: [],
    data: [],
    options: [],
    sort: { 
        prop: sessionStorage.getItem(sortPropKey) || 'date' , 
        order: sessionStorage.getItem(sortOrderKey) || 'descending' 
    }
})

let stocks = useRouteQuery("stocks", "")

const getRawData = async () => { 
    if (props.dtype == "low") {
        const res =await getGB60WLowData();
        state.rawData=res.data;
    } else {
        const res =await getGB60WTopData();
        state.rawData=res.data;
    }

    if (stocks) {
        let stocksArr = stocks.split(";")
        state.rawData = state.rawData.filter(item => stocksArr.includes(item.stock))
    } 
    state.data=state.rawData;
}

getRawData().then(() => {
    state.options = new Set()
    state.rawData.forEach(element => {
        state.options.add(element.date)
    });
    state.options = Array.from(state.options).sort().reverse()
})

const sortChange = (column, prop, order) => {
    sessionStorage.setItem(sortPropKey, column.prop)
    sessionStorage.setItem(sortOrderKey, column.order)
}

const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {
    let columnProperty = column.property
    let val = row[columnProperty]

    if (columnProperty == "lp") {
        return getLpClassName(val)
    }

    if (["curPct","minPct","cur60wPct","nextWeekPct"].includes(columnProperty)) {
        if (val < 0) {
            return "lt0-cell"
        }
    }

    if (columnProperty == "maxPct") {
        if (row.maxPct == row.disPct) {
            return "lt0-cell"
        }
    }
    return ''
}

    const cellClick = (row, column, cell, event) => {
        let columnProperty = column.property
        let val = row[columnProperty]

        if (['stock','industry','date','minDate','maxDate','curPct','cur60wPct','nextWeekPct','category'].includes(columnProperty)) {
            if (state.operationSelected != "" && state.operationSelected == val) {
                state.operationSelected = ""
                state.data = state.rawData
            } else {
                state.operationSelected = val
                if (["curPct","cur60wPct","nextWeekPct"].includes(columnProperty)) {
                    if (val >= 0) {
                        state.data = state.rawData.filter(item => item[columnProperty] >= 0)
                    } else {
                        state.data = state.rawData.filter(item => item[columnProperty] < 0)
                    }
                } else {
                    state.data = state.rawData.filter(item => item[columnProperty] == val)
                    if (columnProperty == 'date') {
                        state.selected = state.operationSelected
                    } else {
                        state.selected = ""
                    }
                }
            }
        }
    }

const change = () => {
    state.operationSelected = state.selected
    state.data = state.rawData.filter(item => item.date == state.selected)
}

const summaryMethod = (param) => { 
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {

        if (index === 0) {
            sums[index] = '汇总：';
            return;
        }

        if (["maxPct","minPct","curPct"].includes(column.property)) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                const validValues = values.filter(value => !isNaN(value));
                if (validValues.length > 0) {
                    const sum = validValues.reduce((prev, curr) => prev + curr, 0);
                    const avg = sum / validValues.length;
                    sums[index] = `平均: ${avg.toFixed(2)}`;
                }
            }
        }
    })
    
    return sums;
}

const getStocks = () => {
    let stocks = []
    state.data.forEach(item => {
        stocks.push(item.stock)
    })
    return stocks
}

const multi = () => {
    openNewTableMulti(getStocks())
}
</script>